package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic("server/vms/test")
@Slf4j
public class TestHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {

        if(StringUtils.isEmpty(jsonMsg)){
            log.error(TopicConfig.VMS_COMPLETED_TOPIC + "消息内容为空");
            return;
        }

        TaskCompleteContract contract = JsonUtil.getByJson(jsonMsg, TaskCompleteContract.class);
        //校验消息内容
        if(contract == null || StringUtils.isEmpty(contract.getInnerCode())){
            log.error(TopicConfig.VMS_COMPLETED_TOPIC + "消息内容不正确:" + jsonMsg);
            return;
        }

        Integer status;
        if(contract.getTaskType() == VMSystem.TASK_TYPE_DEPLOY){
            //投放
            status = VMSystem.VM_STATUS_RUNNING;//运营中
        }else if(contract.getTaskType() == VMSystem.TASK_TYPE_REVOKE){
            //撤机
            status = VMSystem.VM_STATUS_REVOKE;//已经撤机
        }else{
            log.error("消息中的工单类型不正确:" + contract.getTaskType());
            return;
        }

        boolean b = vendingMachineService.updateStatus(contract.getInnerCode(), status);
        if(!b){
            log.error("售货机编码不存在!" + contract.getInnerCode());
        }
    }
}
